<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="isMobile ? '90%' : '400px'"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="verify-content">
<!--      <p class="warning-text">-->
<!--        <i class="fas fa-exclamation-triangle"></i>-->
<!--        {{ warningText }}-->
<!--      </p>-->

<!--      <div class="verify-options">-->
<!--        <el-radio-group v-model="verifyType">-->
<!--          <el-radio label="google">{{ $t('谷歌验证器') }}</el-radio>-->
<!--          <el-radio label="email">{{ $t('邮箱验证码') }}</el-radio>-->
<!--        </el-radio-group>-->
<!--      </div>-->

      <div class="email-info">
        {{ $t('发送至') }}：{{userEmail}}
<!--        {{ maskEmail(userEmail) }}-->
      </div>

      <div class="verify-input-wrapper">
        <el-input
          v-model="verifyCode"
          :placeholder="$t('请输入邮箱验证码')"
          maxlength="6"
        >
          <template #append>
            <el-button
              :disabled="countdown > 0"
              @click="sendEmailCode"
            >
              {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('获取验证码') }}
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">{{ $t('取消') }}</el-button>
      <el-button :type="confirmButtonType" @click="handleConfirm" :loading="loading">
        {{ confirmButtonText }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useAuth } from '@/stores/auth'

export default defineComponent({
  name: 'VerifyDialog'
})
</script>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from "@/store/modules/user";
import {ApiSendEmail} from "@/api/public";
import {useI18n} from "vue-i18n";
const { t } = useI18n();

const props = defineProps<{
  modelValue: boolean
  title?: string
  warningText?: string
  confirmButtonText?: string
  confirmButtonType?: 'primary' | 'success' | 'warning' | 'danger'
}>()

// const { userInfo } = useAuth()
// const userEmail = computed(() => userInfo.value?.email || '')
const userStore = useUserStore()
const userEmail = userStore.userInfo?.member?.email || ''

// 邮箱掩码处理
const maskEmail = (email: string) => {
  if (!email) return ''
  const [name, domain] = email.split('@')
  if (name.length <= 2) return email
  return `${name.slice(0, 2)}****@${domain}`
}

const emit = defineEmits(['update:modelValue', 'cancel', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const verifyType = ref('google')
const verifyCode = ref('')
const loading = ref(false)
const countdown = ref(0)
const newEmailCountdown = ref(0)

// 添加移动端判断
const isMobile = ref(false)

onMounted(() => {
  const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768
  }
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

// 发送邮箱验证码
const sendEmailCode = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    startCountdown('current')
    // countdown.value = 60
    // const timer = setInterval(() => {
    //   countdown.value--
    //   if (countdown.value <= 0) {
    //     clearInterval(timer)
    //   }
    // }, 1000)
    //
    // // TODO: 调用发送验证码接口
    // ElMessage.success('验证码已发送')
  } catch (error: any) {
    ElMessage.error(error.message || t('发送失败'))
  }
}
const startCountdown = async (type: 'current' | 'new') => {
  ApiSendEmail({email: userEmail}).then(res => {
    ElMessage.success(res.msg || t('验证码已发送'))
    const target = type === 'current' ? countdown : newEmailCountdown
    target.value = 60
    const timer = setInterval(() => {
      target.value--
      if (target.value <= 0) clearInterval(timer)
    }, 1000)
  }).catch(() => {
    ElMessage.error(t('发送失败'))
  })
}

// 确认验证
const handleConfirm = async () => {
  if (!verifyCode.value) {
    ElMessage.warning(t('请输入验证码'))
    return
  }

  loading.value = true
  try {
    // 发送验证结果
    emit('confirm', {
      type: verifyType.value,
      code: verifyCode.value
    })
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('cancel')
  handleClose()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  verifyCode.value = ''
  verifyType.value = 'google'
}
</script>

<style lang="scss" scoped>
.verify-content {
  padding: 20px 0;
}

.warning-text {
  color: #f56c6c;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;

  i {
    font-size: 16px;
  }
}

.verify-options {
  margin-bottom: 20px;

  :deep(.el-radio-group) {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  :deep(.el-radio) {
    margin-right: 0;
    height: auto;
    padding: 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    &.is-checked {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }
  }
}

.email-info {
  font-size: 13px;
  color: #909399;
  margin-bottom: 16px;
}

.verify-input-wrapper {
  :deep(.el-input-group__append) {
    padding: 0;

    .el-button {
      margin: 0;
      border: none;
      padding: 0 15px;

      &:not(:disabled):hover {
        color: var(--el-color-primary);
        background: var(--el-fill-color-light);
      }
    }
  }
}

@media screen and (max-width: 768px) {
  :deep(.el-dialog) {
    margin: 20vh auto 0 !important;

    .el-dialog__body {
      padding: 20px 16px;
    }

    .el-dialog__footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 16px;
      background: #fff;
      border-top: 1px solid #eee;
      display: flex;
      gap: 12px;

      .el-button {
        flex: 1;
        margin: 0;
      }
    }
  }

  .verify-content {
    padding-bottom: 80px;
  }
}
</style>
